package com.hyc.myvideo.ui.view;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import com.acmenxd.toaster.Toaster;
import com.hyc.myvideo.R;
import com.hyc.myvideo.ui.service.OnVideoEventListener;
import com.hyc.myvideo.utils.PlayerUtils;
import com.hyc.myvideo.widget.ProgressWheel;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import timber.log.Timber;

/**
 * Created by maning on 16/6/14.
 * 播放器
 */
public class MNViderPlayer extends FrameLayout
    implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, SurfaceHolder.Callback,
    GestureDetector.OnGestureListener, MediaPlayer.OnCompletionListener,
    MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
    MediaPlayer.OnBufferingUpdateListener {

  private Context context;
  private Activity activity;

  static final Handler myHandler = new Handler(Looper.getMainLooper()) {
  };

  // SurfaceView的创建比较耗时，要注意
  private SurfaceHolder surfaceHolder;
  private MediaPlayer mediaPlayer;

  //标记暂停和播放状态
  private boolean isPlaying = true;

  //地址
  private String videoPath;
  private int video_position = 0;

  //控件的位置信息
  private float mediaPlayerX;
  private float mediaPlayerY;
  private int playerViewW;
  private int playerViewH;

  // 计时器
  private Timer timer_video_time;
  private TimerTask task_video_timer;
  private Timer timer_controller;
  private TimerTask task_controller;

  //是否是横屏
  private boolean isFullscreen = false;
  private boolean isPrepare = false;
  private boolean isNeedNetChangeListen = true;
  private boolean isFirstPlay = false;

  private boolean isPlay=true;

  //默认宽高比16:9
  private int defaultWidthProportion = 16;
  private int defaultHeightProportion = 9;

  //控件

  /** 背景 */
  private LinearLayout mn_player_surface_bg;
  /** 底部菜单模块 */
  private RelativeLayout mn_rl_bottom_menu;
  /** SurfaceView */
  private SurfaceView mn_palyer_surfaceView;
  /** 底部菜单模块的播放 */
  private ImageView mn_iv_play_pause;
  /** 底部菜单模块的全屏 */
  private ImageView mn_iv_fullScreen;
  /** 底部菜单模块的开始时间 */
  private TextView mStartTime;
  /** 底部菜单模块的总时间 */
  private TextView mEndTime;
  private SeekBar mn_seekBar;
  /** 顶部菜单模块 */
  private RelativeLayout mn_rl_top_menu;
  /** 顶部菜单模块的返回 */
  private ImageView mn_iv_back;
  /** 顶部菜单模块的下载 */
  private ImageView mn_iv_download;
  /** 顶部菜单模块的添加 */
  private ImageView mv_iv_add;
  /** 顶部菜单模块的添加 */
  private ImageView mn_iv_share;

  /** 中间菜单模块 */
  private RelativeLayout mn_player_rl_progress;
  /** 加载出错...\n点击重新加载 */
  private LinearLayout mn_player_ll_error;
  /** 网络断开 \n 点击重新加载 */
  private LinearLayout mn_player_ll_net;
  /** 中间的加载动画 */
  private ProgressWheel mn_player_progressBar;
  /** 中间的播放 */
  private ImageView mn_player_iv_play_center;
  /** 缩略图 */
  private ImageView iv_video_thumbnail;

  public MNViderPlayer(Context context) {
    this(context, null);
  }

  public MNViderPlayer(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public MNViderPlayer(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    this.context = context;
    activity = (Activity) this.context;
    //自定义属性相关
    initAttrs(context, attrs);
    //其他
    init();
  }

  private void initAttrs(Context context, AttributeSet attrs) {
    //获取自定义属性
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MNViderPlayer);
    //遍历拿到自定义属性
    for (int i = 0; i < typedArray.getIndexCount(); i++) {
      int index = typedArray.getIndex(i);
      if (index == R.styleable.MNViderPlayer_mnFirstNeedPlay) {
        isFirstPlay = typedArray.getBoolean(R.styleable.MNViderPlayer_mnFirstNeedPlay, false);
      }
    }
    //销毁
    typedArray.recycle();
  }

  @Override public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    int screenWidth = PlayerUtils.getScreenWidth(activity);
    int screenHeight = PlayerUtils.getScreenHeight(activity);
    ViewGroup.LayoutParams layoutParams = getLayoutParams();

    //newConfig.orientation获得当前屏幕状态是横向或者竖向
    //Configuration.ORIENTATION_PORTRAIT 表示竖向
    //Configuration.ORIENTATION_LANDSCAPE 表示横屏
    if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
      activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
      //计算视频的大小16：9
      layoutParams.width = screenWidth;
      layoutParams.height = screenWidth * defaultHeightProportion / defaultWidthProportion;
      setX(mediaPlayerX);
      setY(mediaPlayerY);
    }
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
      layoutParams.width = screenWidth;
      layoutParams.height = screenHeight;

      setX(0);
      setY(0);
    }
    setLayoutParams(layoutParams);

    playerViewW = screenWidth;
    playerViewH = layoutParams.height;

    //适配大小
    fitVideoSize();
  }

  //初始化
  private void init() {
    View inflate = View.inflate(context, R.layout.mn_player_view, this);
    mn_rl_bottom_menu = (RelativeLayout) inflate.findViewById(R.id.mn_rl_bottom_menu);
    mn_palyer_surfaceView = (SurfaceView) inflate.findViewById(R.id.mn_palyer_surfaceView);
    mn_iv_play_pause = (ImageView) inflate.findViewById(R.id.mn_iv_play_pause);
    mn_iv_fullScreen = (ImageView) inflate.findViewById(R.id.mn_iv_fullScreen);
    mStartTime = (TextView) inflate.findViewById(R.id.mn_tv_time_start);
    mEndTime = (TextView) inflate.findViewById(R.id.mn_tv_time_end);
    mn_seekBar = (SeekBar) inflate.findViewById(R.id.mn_seekBar);
    mn_iv_back = (ImageView) inflate.findViewById(R.id.mn_iv_back);
    mn_iv_download = (ImageView) inflate.findViewById(R.id.mn_iv_download);
    mv_iv_add = (ImageView) inflate.findViewById(R.id.mv_iv_add);
    mn_iv_share = (ImageView) inflate.findViewById(R.id.mn_iv_share);
    mn_rl_top_menu = (RelativeLayout) inflate.findViewById(R.id.mn_rl_top_menu);
    mn_player_rl_progress = (RelativeLayout) inflate.findViewById(R.id.mn_player_rl_progress);
    mn_player_ll_error = (LinearLayout) inflate.findViewById(R.id.mn_player_ll_error);
    mn_player_ll_net = (LinearLayout) inflate.findViewById(R.id.mn_player_ll_net);
    mn_player_progressBar = (ProgressWheel) inflate.findViewById(R.id.mn_player_progressBar);
    mn_player_iv_play_center = (ImageView) inflate.findViewById(R.id.mn_player_iv_play_center);
    mn_player_surface_bg = (LinearLayout) inflate.findViewById(R.id.mn_player_surface_bg);
    iv_video_thumbnail = (ImageView) inflate.findViewById(R.id.iv_video_thumbnail);

    mn_seekBar.setOnSeekBarChangeListener(this);
    mn_iv_play_pause.setOnClickListener(this);
    mn_iv_fullScreen.setOnClickListener(this);
    mn_iv_back.setOnClickListener(this);
    mn_iv_download.setOnClickListener(this);
    mv_iv_add.setOnClickListener(this);
    mn_iv_share.setOnClickListener(this);
    mn_player_ll_error.setOnClickListener(this);
    mn_player_ll_net.setOnClickListener(this);
    mn_player_iv_play_center.setOnClickListener(this);

    //初始化
    initViews();

    //if (!isFirstPlay) {
    mn_player_iv_play_center.setVisibility(View.VISIBLE);
    mn_player_progressBar.setVisibility(View.GONE);
    //}

    //初始化SurfaceView
    initSurfaceView();

    //初始化手势
    initGesture();

    //存储控件的位置信息
    myHandler.postDelayed(new Runnable() {
      @Override public void run() {
        mediaPlayerX = getX();
        mediaPlayerY = getY();
        playerViewW = getWidth();
        playerViewH = getHeight();
        Timber.e("控件信息---X：" + mediaPlayerX + "，Y：" + mediaPlayerY);
        Timber.e("控件信息---playerViewW：" + playerViewW + "，playerViewH：" + playerViewH);
      }
    }, 1000);
  }

  private void initViews() {

    mn_palyer_surfaceView.setAlpha(0);

    mn_rl_bottom_menu.setVisibility(View.GONE);
    mn_rl_top_menu.setVisibility(View.GONE);
    mn_player_rl_progress.setVisibility(View.VISIBLE);
    mn_player_progressBar.setVisibility(View.VISIBLE);
    mn_player_ll_error.setVisibility(View.GONE);
    mn_player_ll_net.setVisibility(View.GONE);
    mn_player_iv_play_center.setVisibility(View.GONE);
    mn_rl_top_menu.setVisibility(View.VISIBLE);
  }

  /**
   * 设置缩略图
   */
  private void setVideoThumbnail() {
    if (PlayerUtils.isNetworkConnected(context)) {
      new Thread(new Runnable() {
        @Override public void run() {
          final Bitmap videoThumbnail =
              PlayerUtils.createVideoThumbnail(videoPath, getWidth(), getHeight());
          myHandler.post(new Runnable() {
            @Override public void run() {
              if (videoThumbnail != null) {
                iv_video_thumbnail.setVisibility(View.VISIBLE);
                iv_video_thumbnail.setImageBitmap(videoThumbnail);
              } else {
                iv_video_thumbnail.setVisibility(View.GONE);
              }
            }
          });
        }
      }).start();
    }
  }

  /**
   * 初始化SurfaceView
   */
  private void initSurfaceView() {
    Timber.e("initSurfaceView");
    // 得到SurfaceView容器，播放的内容就是显示在这个容器里面
    surfaceHolder = mn_palyer_surfaceView.getHolder();
    surfaceHolder.setKeepScreenOn(true);
    // SurfaceView的一个回调方法
    surfaceHolder.addCallback(this);
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      case R.id.mn_iv_play_pause://底部菜单模块的播放
        if (mediaPlayer != null) {
          if (mediaPlayer.isPlaying()) {
            pauseVideo();
            mn_player_iv_play_center.setVisibility(VISIBLE);
          } else {
            startVideo();
          }
        }
        break;
      case R.id.mn_iv_fullScreen://底部菜单模块的全屏
        if (isFullscreen) {
          setProtrait();
        } else {
          setLandscape();
        }
        break;
      case R.id.mn_iv_back://顶部菜单模块的返回
        if (isFullscreen) {
          setProtrait();
        } else if (videoEventListener != null) {
          //返回
          videoEventListener.onFinish();
        }
        break;
      case R.id.mn_iv_download:
        if (videoEventListener != null) {
          videoEventListener.onDownload();
        }
        break;
      case R.id.mv_iv_add:
        if (videoEventListener != null) {
          videoEventListener.onAddToCatalog();
        }
        break;
      case R.id.mn_iv_share:
        if (videoEventListener != null) {
          videoEventListener.onShare();
        }
        break;
      case R.id.mn_player_ll_error:
      case R.id.mn_player_ll_net:
        playVideo(videoPath, 0);
        break;
      case R.id.mn_player_iv_play_center:
        if (isPlay){
          playVideo(videoPath, 0);
          isPlay=false;
        }else if (!mediaPlayer.isPlaying()){
          startVideo();
        }
        break;
    }
  }

  //--------------------------------------------------------------------------------------
  // ######## 相关View的操作 ########
  //--------------------------------------------------------------------------------------

  //下面菜单的显示和隐藏
  private void initBottomMenuState() {
    if (mn_rl_bottom_menu.getVisibility() == View.GONE) {
      initControllerTask();
      mn_rl_bottom_menu.setVisibility(View.VISIBLE);
      mn_rl_top_menu.setVisibility(View.VISIBLE);
      if (!mediaPlayer.isPlaying()){

        mn_player_iv_play_center.setVisibility(VISIBLE);
      }
    } else {
      destroyControllerTask(true);
    }
  }

  private void dismissControllerMenu() {
    mn_rl_top_menu.setVisibility(View.GONE);
    mn_rl_bottom_menu.setVisibility(View.GONE);
    mn_player_iv_play_center.setVisibility(GONE);
  }

  private void showErrorView() {
    mn_player_iv_play_center.setVisibility(View.GONE);
    mn_player_ll_net.setVisibility(View.GONE);
    mn_player_progressBar.setVisibility(View.GONE);
    mn_player_ll_error.setVisibility(View.VISIBLE);
    iv_video_thumbnail.setVisibility(View.GONE);
  }

  private void showNoNetView() {
    mn_player_iv_play_center.setVisibility(View.GONE);
    mn_player_ll_net.setVisibility(View.VISIBLE);
    mn_player_progressBar.setVisibility(View.GONE);
    mn_player_ll_error.setVisibility(View.GONE);
    iv_video_thumbnail.setVisibility(View.GONE);
  }

  /**
   * 设置横屏
   */
  private void setLandscape() {
    isFullscreen = true;
    ((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
  }

  /**
   * 设置竖屏
   */
  private void setProtrait() {
    isFullscreen = false;
    ((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  }

  //--------------------------------------------------------------------------------------
  // ######## 计时器相关操作 ########
  //--------------------------------------------------------------------------------------

  /**
   * 初始化Timer
   */
  private void initTimeTask() {
    timer_video_time = new Timer();
    task_video_timer = new TimerTask() {
      @Override public void run() {
        myHandler.post(new Runnable() {
          @Override public void run() {
            if (mediaPlayer == null) {
              return;
            }
            //设置时间
            mStartTime.setText(PlayerUtils.converLongTimeToStr(mediaPlayer.getCurrentPosition()));
            mEndTime.setText(PlayerUtils.converLongTimeToStr(mediaPlayer.getDuration()));

            //进度条
            int progress = mediaPlayer.getCurrentPosition();
            mn_seekBar.setProgress(progress);
          }
        });
      }
    };
    //每秒执行一次
    timer_video_time.schedule(task_video_timer, 0, 1000);
  }

  /**
   * 销毁Timer
   */
  private void destroyTimeTask() {
    if (timer_video_time != null && task_video_timer != null) {
      timer_video_time.cancel();
      task_video_timer.cancel();
      timer_video_time = null;
      task_video_timer = null;
    }
  }

  /**
   * 设置计时器,控制器的影藏和显示
   */
  private void initControllerTask() {
    // 设置计时器,控制器的影藏和显示
    timer_controller = new Timer();
    task_controller = new TimerTask() {
      @Override public void run() {
        destroyControllerTask(false);
      }
    };
    timer_controller.schedule(task_controller, 5000);
    initTimeTask();
  }

  private void destroyControllerTask(boolean isMainThread) {
    if (isMainThread) {
      dismissControllerMenu();
    } else {
      myHandler.post(new Runnable() {
        @Override public void run() {
          dismissControllerMenu();
        }
      });
    }
    if (timer_controller != null && task_controller != null) {
      timer_controller.cancel();
      task_controller.cancel();
      timer_controller = null;
      task_controller = null;
    }
    destroyTimeTask();
  }

  //--------------------------------------------------------------------------------------
  // ######## 接口方法实现 ########
  //--------------------------------------------------------------------------------------
  @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    Timber.e("==onProgressChanged==" + progress + "===fromUser===" + fromUser);
  }

  @Override public void onStartTrackingTouch(SeekBar seekBar) {

  }

  @Override public void onStopTrackingTouch(SeekBar seekBar) {
    Timber.e("====onStopTrackingTouch=====" + seekBar.getMax());
    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
      int maxCanSeekTo = seekBar.getMax() - 5 * 1000;
      if (seekBar.getProgress() < maxCanSeekTo) {
        mediaPlayer.seekTo(seekBar.getProgress());
      } else {
        //不能拖到最后
        mediaPlayer.seekTo(maxCanSeekTo);
      }
    }
  }

  //播放
  @Override public void surfaceCreated(SurfaceHolder holder) {
    Timber.e("surfaceCreated");
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setDisplay(holder); // 添加到容器中
    //播放完成的监听
    mediaPlayer.setOnCompletionListener(this);
    // 异步准备的一个监听函数，准备好了就调用里面的方法
    mediaPlayer.setOnPreparedListener(this);
    //播放错误的监听
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnBufferingUpdateListener(this);
    //第一次初始化需不需要主动播放
    if (isFirstPlay) {
      //判断当前有没有网络（播放的是网络视频）
      if (!PlayerUtils.isNetworkConnected(context) && videoPath.startsWith("http")) {
        Toaster.show(context.getString(R.string.mnPlayerNoNetHint));
        showNoNetView();
      } else {
        //手机网络给提醒
        if (PlayerUtils.isMobileConnected(context)) {
          Toaster.show(context.getString(R.string.mnPlayerMobileNetHint));
        }
        //添加播放路径
        try {
          mediaPlayer.setDataSource(videoPath);
          // 准备开始,异步准备，自动在子线程中
          mediaPlayer.prepareAsync();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    isFirstPlay = true;
  }

  @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    Timber.e("surfaceChanged---width：" + width + ",height:" + height);
  }

  @Override public void surfaceDestroyed(SurfaceHolder holder) {
    //保存播放位置
    if (mediaPlayer != null) {
      mediaPlayer.pause();
      mn_iv_play_pause.setImageResource(R.mipmap.video_play);
      //mn_player_iv_play_center
      video_position = mediaPlayer.getCurrentPosition();
    }
    destroyControllerTask(true);
    Timber.e("surfaceDestroyed---video_position：" + video_position);
  }

  //MediaPlayer
  @Override public void onCompletion(MediaPlayer mediaPlayer) {
    mn_iv_play_pause.setImageResource(R.mipmap.video_play);
    //mn_player_iv_play_center
    isPlaying = false;
    destroyControllerTask(true);
    video_position = 0;
    if (onCompletionListener != null) {
      onCompletionListener.onCompletion(mediaPlayer);
    }
  }

  @Override public void onBufferingUpdate(MediaPlayer mp, int percent) {
    Timber.e("二级缓存onBufferingUpdate: " + percent);
    if (percent >= 0 && percent <= 100) {
      int secondProgress = mp.getDuration() * percent / 100;
      mn_seekBar.setSecondaryProgress(secondProgress);
    }
  }

  @Override public boolean onError(MediaPlayer mp, int what, int extra) {
    Timber.e("发生错误error:" + what);
    if (what != -38) {  //这个错误不管
      showErrorView();
    }
    return true;
  }

  @Override public void onPrepared(final MediaPlayer mediaPlayer) {

    mediaPlayer.start(); // 开始播放
    //是否开始播放
    if (!isPlaying) {
      mediaPlayer.pause();
      mn_iv_play_pause.setImageResource(R.mipmap.video_play);
    } else {
      mn_iv_play_pause.setImageResource(R.mipmap.video_pause);
    }
    isPrepare = true;
    // 把得到的总长度和进度条的匹配
    mn_seekBar.setMax(mediaPlayer.getDuration());
    //延时：避免出现上一个视频的画面闪屏
    myHandler.postDelayed(new Runnable() {
      @Override public void run() {
        initBottomMenuState();
        mn_player_rl_progress.setVisibility(View.GONE);

        //跳转指定位置
        if (video_position > 0) {
          Timber.e("onPrepared---video_position:" + video_position);
          mediaPlayer.seekTo(video_position);
          video_position = 0;
        }
      }
    }, 500);
    //适配大小
    fitVideoSize();

    //恢复显示,隐藏列缩图
    mn_palyer_surfaceView.setAlpha(1);
    iv_video_thumbnail.setVisibility(View.GONE);
  }

  private void fitVideoSize() {
    if (mediaPlayer == null) {
      return;
    }
    //适配视频的高度
    int videoWidth = mediaPlayer.getVideoWidth();
    int videoHeight = mediaPlayer.getVideoHeight();
    int parentWidth = playerViewW;
    int parentHeight = playerViewH;
    int screenWidth = PlayerUtils.getScreenWidth(activity);
    int screenHeight = PlayerUtils.getScreenHeight(activity);

    //判断视频宽高和父布局的宽高
    int surfaceViewW;
    int surfaceViewH;
    if ((float) videoWidth / (float) videoHeight > (float) parentWidth / (float) parentHeight) {
      surfaceViewW = parentWidth;
      surfaceViewH = videoHeight * surfaceViewW / videoWidth;
    } else {
      surfaceViewH = parentHeight;
      surfaceViewW = videoWidth * parentHeight / videoHeight;
    }

    Timber.e("fitVideoSize---"
        + "videoWidth："
        + videoWidth
        + ",videoHeight:"
        + videoHeight
        + ",parentWidth:"
        + parentWidth
        + ",parentHeight:"
        + parentHeight
        + ",screenWidth:"
        + screenWidth
        + ",screenHeight:"
        + screenHeight
        + ",surfaceViewW:"
        + surfaceViewW
        + ",surfaceViewH:"
        + surfaceViewH);
    //改变surfaceView的大小
    ViewGroup.LayoutParams params = mn_player_surface_bg.getLayoutParams();
    params.height = surfaceViewH;
    params.width = surfaceViewW;
    mn_player_surface_bg.setLayoutParams(params);
  }

  //--------------------------------------------------------------------------------------
  // ######## 手势相关 ########
  //--------------------------------------------------------------------------------------
  private GestureDetector gestureDetector;
  /** 设定进度滑动时的步长，避免每次滑动都改变，导致改变过快 */
  private static final float STEP_PROGRESS = 2f;

  /**
   * 初始化手势
   */
  private void initGesture() {

    gestureDetector = new GestureDetector(getContext(), this);
    setLongClickable(true);
    gestureDetector.setIsLongpressEnabled(true);
  }

  @Override public boolean onDown(MotionEvent e) {
    return true;
  }

  @Override public void onShowPress(MotionEvent e) {
  }

  @Override public boolean onSingleTapUp(MotionEvent e) {
    if (!isPrepare) {
      return false;
    }
    initBottomMenuState();
    return false;
  }

  @Override
  public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

    if (!isPrepare) {
      return false;
    }

    // 横向的距离变化大则调整进度，纵向的变化大则调整音量
    if (mediaPlayer != null && mediaPlayer.isPlaying()) {

      //表示是横向滑动,可以添加快进
      // distanceX=lastScrollPositionX-currentScrollPositionX，因此为正时是快进
      mn_rl_top_menu.setVisibility(View.VISIBLE);
      mn_rl_bottom_menu.setVisibility(View.VISIBLE);
      try {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
          if (Math.abs(distanceX) > Math.abs(distanceY)) {// 横向移动大于纵向移动
            if (distanceX >= PlayerUtils.dip2px(context, STEP_PROGRESS)) {// 快退，用步长控制改变速度，可微调
              if (mediaPlayer.getCurrentPosition() > 3 * 1000) {// 避免为负
                int cpos = mediaPlayer.getCurrentPosition();
                mediaPlayer.seekTo(cpos - 3000);
                mn_seekBar.setProgress(mediaPlayer.getCurrentPosition());
              } else {
                //什么都不做
                mediaPlayer.seekTo(3000);
              }
            } else if (distanceX <= -PlayerUtils.dip2px(context, STEP_PROGRESS)) {// 快进
              if (mediaPlayer.getCurrentPosition()
                  < mediaPlayer.getDuration() - 5 * 1000) {// 避免超过总时长
                int cpos = mediaPlayer.getCurrentPosition();
                mediaPlayer.seekTo(cpos + 3000);
                // 把当前位置赋值给进度条
                mn_seekBar.setProgress(mediaPlayer.getCurrentPosition());
              }
            }
          }
          mStartTime.setText(PlayerUtils.converLongTimeToStr(mediaPlayer.getCurrentPosition()));
        }
      } catch (IllegalStateException e) {
        e.printStackTrace();
      }
    }
    return false;
  }

  @Override public void onLongPress(MotionEvent e) {
  }

  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    return false;
  }

  @Override public boolean onTouchEvent(MotionEvent event) {
    // 手势里除了singleTapUp，没有其他检测up的方法
    return gestureDetector.onTouchEvent(event);
  }

  //--------------------------------------------------------------------------------------
  // ######## 对外提供的方法 ########
  //--------------------------------------------------------------------------------------

  /**
   * 设置宽高比:默认16:9
   */
  public void setWidthAndHeightProportion(int width, int height) {
    this.defaultWidthProportion = width;
    this.defaultHeightProportion = height;
  }

  /**
   * 设置视频信息
   *
   * @param url 视频地址
   */
  public void setDataSource(String url) {
    //赋值
    videoPath = url;

    setVideoThumbnail();
  }

  /**
   * 播放视频（支持上次播放位置）
   * 自己记录上一次播放的位置，然后传递position进来就可以了
   *
   * @param url 视频地址
   * @param position 视频跳转的位置(毫秒)
   */
  public void playVideo(String url, int position) {
    //地址判空处理
    if (TextUtils.isEmpty(url)) {
      Toaster.show(context.getString(R.string.mnPlayerUrlEmptyHint));
      return;
    }
    //销毁ControllerView
    destroyControllerTask(true);

    //赋值
    videoPath = url;
    video_position = position;
    isPrepare = false;
    isPlaying = true;

    //初始化View
    initViews();

    //判断当前有没有网络（播放的是网络视频）
    if (!PlayerUtils.isNetworkConnected(context) && url.startsWith("http")) {
      Toaster.show(context.getString(R.string.mnPlayerNoNetHint));
      showNoNetView();
      return;
    }
    //手机网络给提醒
    if (PlayerUtils.isMobileConnected(context) && url.startsWith("http")) {
      //Toaster.show(context.getString(R.string.mnPlayerMobileNetHint));
    }

    //重置MediaPlayer
    resetMediaPlayer();

    //网络监听的广播
    if (isNeedNetChangeListen) {
      registerNetReceiver();
    } else {
      unregisterNetReceiver();
    }
  }

  @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void resetMediaPlayer() {
    try {
      if (mediaPlayer != null) {
        if (mediaPlayer.isPlaying()) {
          mediaPlayer.pause();
          mediaPlayer.stop();
        }
        //重置mediaPlayer
        mediaPlayer.reset();
        isPlay=true;
        //添加播放路径
        mediaPlayer.setDataSource(videoPath);
        // 准备开始,异步准备，自动在子线程中
        mediaPlayer.prepareAsync();
        //视频缩放模式
        mediaPlayer.setVideoScalingMode(android.media.MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT);
      } else {
        //TODO:播放器初始化失败后怎么操作
        //Toast.makeText(context, "播放器初始化失败", Toast.LENGTH_SHORT).show();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 播放视频
   */
  public void startVideo() {
    if (mediaPlayer != null) {
      mediaPlayer.start();
      mn_iv_play_pause.setImageResource(R.mipmap.video_pause);
      mn_player_iv_play_center.setVisibility(GONE);
      isPlaying = true;
    }
  }

  /**
   * 暂停视频
   */
  public void pauseVideo() {
    if (mediaPlayer != null) {
      mediaPlayer.pause();
      mn_iv_play_pause.setImageResource(R.mipmap.video_play);
      video_position = mediaPlayer.getCurrentPosition();
      isPlaying = false;
    }
  }

  /**
   * 竖屏
   */
  public void setOrientationPortrait() {
    setProtrait();
  }

  /**
   * 横屏
   */
  public void setOrientationLandscape() {
    setLandscape();
  }

  /**
   * 设置是否需要网络变化监听
   */
  public void setIsNeedNetChangeListen(boolean isNeedNetChangeListen) {
    this.isNeedNetChangeListen = isNeedNetChangeListen;
  }

  /**
   * 判断是不是全屏状态
   */
  public boolean isFullScreen() {
    return isFullscreen;
  }

  /**
   * 获取当前播放的位置
   */
  public int getVideoCurrentPosition() {
    int position = 0;
    if (mediaPlayer != null) {
      position = mediaPlayer.getCurrentPosition();
    }
    return position;
  }

  /**
   * 获取视频总长度
   */
  public int getVideoTotalDuration() {
    int position = 0;
    if (mediaPlayer != null) {
      position = mediaPlayer.getDuration();
    }
    return position;
  }

  /**
   * 获取管理者
   */
  public MediaPlayer getMediaPlayer() {
    return mediaPlayer;
  }

  /**
   * 销毁资源
   */
  public void destroyVideo() {
    if (mediaPlayer != null) {
      mediaPlayer.stop();
      mediaPlayer.release();// 释放资源
      mediaPlayer = null;
    }
    surfaceHolder = null;
    mn_palyer_surfaceView = null;
    video_position = 0;
    unregisterNetReceiver();
    removeAllListener();
    destroyTimeTask();
    myHandler.removeCallbacksAndMessages(null);
  }

  //-------------------------网络变化监听
  public class NetChangeReceiver extends BroadcastReceiver {
    @Override public void onReceive(Context context, Intent intent) {
      if (onNetChangeListener == null || !isNeedNetChangeListen) {
        return;
      }
      ConnectivityManager connectivityManager =
          (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
      if (netInfo != null && netInfo.isAvailable()) {
        if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) { //WiFi网络
          onNetChangeListener.onWifi(mediaPlayer);
        } else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {   //3g网络
          onNetChangeListener.onMobile(mediaPlayer);
        } else {    //其他
          Timber.e("其他网络");
        }
      } else {
        onNetChangeListener.onNoAvailable(mediaPlayer);
      }
    }
  }

  private NetChangeReceiver netChangeReceiver;

  private void registerNetReceiver() {
    if (netChangeReceiver == null) {
      IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
      netChangeReceiver = new NetChangeReceiver();
      context.registerReceiver(netChangeReceiver, filter);
    }
  }

  private void unregisterNetReceiver() {
    if (netChangeReceiver != null) {
      context.unregisterReceiver(netChangeReceiver);
    }
  }

  //--------------------------------------------------------------------------------------
  // ######## 自定义回调 ########
  //--------------------------------------------------------------------------------------

  private void removeAllListener() {
    if (onNetChangeListener != null) {
      onNetChangeListener = null;
    }
    if (onPlayerCreatedListener != null) {
      onPlayerCreatedListener = null;
    }
  }

  //网络监听回调
  private OnNetChangeListener onNetChangeListener;

  public void setOnNetChangeListener(OnNetChangeListener onNetChangeListener) {
    this.onNetChangeListener = onNetChangeListener;
  }

  public interface OnNetChangeListener {
    //wifi
    void onWifi(MediaPlayer mediaPlayer);

    //手机
    void onMobile(MediaPlayer mediaPlayer);

    //不可用
    void onNoAvailable(MediaPlayer mediaPlayer);
  }

  //SurfaceView初始化完成回调
  private OnPlayerCreatedListener onPlayerCreatedListener;

  public void setOnPlayerCreatedListener(OnPlayerCreatedListener onPlayerCreatedListener) {
    this.onPlayerCreatedListener = onPlayerCreatedListener;
  }

  public interface OnPlayerCreatedListener {
    //不可用
    void onPlayerCreated(String url, String title);
  }

  //-----------------------播放完回调
  private OnCompletionListener onCompletionListener;

  public void setOnCompletionListener(OnCompletionListener onCompletionListener) {
    this.onCompletionListener = onCompletionListener;
  }

  public interface OnCompletionListener {
    void onCompletion(MediaPlayer mediaPlayer);
  }

  //视频播放监听器
  private OnVideoEventListener videoEventListener;

  public void setVideoEventListener(OnVideoEventListener videoEventListener) {
    this.videoEventListener = videoEventListener;
  }
}